package com.zhuhjay.common.base.model.domain;

import com.zhuhjay.common.base.annotation.ApiLimiter;
import com.zhuhjay.common.base.constant.ApiLimiterConstants;
import com.zhuhjay.common.base.enums.LimiterEnums;
import lombok.Builder;
import lombok.Data;

import static com.zhuhjay.common.base.enums.LimiterEnums.IP;

/**
 * 限流详情
 * @author ZhuHJay
 * @date 2023/8/4 19:40
 */
@Data
@Builder
public class LimiterDetail {

    /** 限流目标 */
    private String target;
    private int limit;
    private int expire;
    private LimiterEnums strategy;
    private String message;

    /**
     * 通过注解构建限流详情
     * 构建规则：ApiLimiter注解优先级高于默认值
     *
     * @param target 限流目标
     * @param apiLimiter 限流注解
     * @return 限流详情
     */
    public static LimiterDetail of(String target, ApiLimiter apiLimiter) {
        if (apiLimiter == null) {
            return LimiterDetail.builder()
                    .target(target)
                    .limit(ApiLimiterConstants.DEFAULT_LIMIT)
                    .expire(ApiLimiterConstants.DEFAULT_EXPIRE)
                    .strategy(IP)
                    .message(ApiLimiterConstants.DEFAULT_MESSAGE)
                    .build();
        }
        return LimiterDetail.builder()
                .target(target)
                .limit(apiLimiter.limit())
                .expire(apiLimiter.expire())
                .strategy(apiLimiter.strategy())
                .message(apiLimiter.message())
                .build();
    }
}
